Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.93% covered (success)
94.93%
131 / 138
60.00% covered (warning)
60.00%
3 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApieServiceProvider
94.93% covered (success)
94.93%
131 / 138
60.00% covered (warning)
60.00%
3 / 5
31.13
0.00% covered (danger)
0.00%
0 / 1
 autoTagHashmapActions
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
 boot
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 register
92.41% covered (success)
92.41%
73 / 79
0.00% covered (danger)
0.00%
0 / 1
18.14
 parseConfig
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
4
 sanitizeConfig
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Apie\LaravelApie;
3
4use Apie\AiInstructor\AiInstructorServiceProvider;
5use Apie\ApieCommonPlugin\ApieCommonPluginServiceProvider;
6use Apie\ApieFileSystem\ApieFileSystemServiceProvider;
7use Apie\CmsApiDropdownOption\CmsDropdownServiceProvider;
8use Apie\Common\AddBasicAuthServiceProvider;
9use Apie\Common\CommonServiceProvider;
10use Apie\Common\ContextBuilders\FrameworkContextBuilder;
11use Apie\Common\Interfaces\BoundedContextSelection;
12use Apie\Common\Interfaces\DashboardContentFactoryInterface;
13use Apie\Common\Wrappers\BoundedContextHashmapFactory;
14use Apie\Common\Wrappers\ConsoleCommandFactory as CommonConsoleCommandFactory;
15use Apie\Console\ConsoleServiceProvider;
16use Apie\Core\CoreServiceProvider;
17use Apie\Core\Session\CsrfTokenProvider;
18use Apie\DoctrineEntityConverter\DoctrineEntityConverterProvider;
19use Apie\DoctrineEntityDatalayer\Commands\ApieUpdateIdfCommand;
20use Apie\DoctrineEntityDatalayer\DoctrineEntityDatalayerServiceProvider;
21use Apie\DoctrineEntityDatalayer\EntityReindexer;
22use Apie\DoctrineEntityDatalayer\IndexStrategy\BackgroundIndexStrategy;
23use Apie\DoctrineEntityDatalayer\IndexStrategy\DirectIndexStrategy;
24use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexAfterResponseIsSentStrategy;
25use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexStrategyInterface;
26use Apie\Export\ExportServiceProvider;
27use Apie\Faker\FakerServiceProvider;
28use Apie\HtmlBuilders\ErrorHandler\CmsErrorRenderer;
29use Apie\HtmlBuilders\HtmlBuilderServiceProvider;
30use Apie\LaravelApie\Config\LaravelConfiguration;
31use Apie\LaravelApie\ContextBuilders\CsrfTokenContextBuilder;
32use Apie\LaravelApie\ContextBuilders\RegisterBoundedContextActionContextBuilder;
33use Apie\LaravelApie\ContextBuilders\SessionContextBuilder;
34use Apie\LaravelApie\ErrorHandler\ApieErrorRenderer;
35use Apie\LaravelApie\ErrorHandler\Handler;
36use Apie\LaravelApie\Providers\CmsServiceProvider;
37use Apie\LaravelApie\Providers\SecurityServiceProvider;
38use Apie\LaravelApie\Wrappers\Cms\DashboardContentFactory;
39use Apie\LaravelApie\Wrappers\Core\BoundedContextSelected;
40use Apie\LaravelApie\Wrappers\Queue\BackgroundProcessPersistListener;
41use Apie\Maker\MakerServiceProvider;
42use Apie\McpServer\McpServerServiceProvider;
43use Apie\RestApi\RestApiServiceProvider;
44use Apie\SchemaGenerator\SchemaGeneratorServiceProvider;
45use Apie\Serializer\SerializerServiceProvider;
46use Apie\ServiceProviderGenerator\TagMap;
47use Apie\TypescriptClientBuilder\TypescriptClientBuilderServiceProvider;
48use Apie\Webdav\WebdavServiceProvider;
49use Illuminate\Config\Repository;
50use Illuminate\Contracts\Debug\ExceptionHandler;
51use Illuminate\Contracts\Events\Dispatcher;
52use Illuminate\Support\ServiceProvider;
53use Psr\EventDispatcher\EventDispatcherInterface;
54use Psr\Http\Message\ServerRequestInterface;
55use Symfony\Component\Config\ConfigCache;
56use Symfony\Component\Config\Definition\Processor;
57use Symfony\Component\Config\Resource\ReflectionClassResource;
58use Symfony\Component\Console\Application;
59use Symfony\Component\EventDispatcher\EventDispatcher;
60use Symfony\Component\Lock\LockFactory;
61
62class ApieServiceProvider extends ServiceProvider
63{
64    /**
65     * @var array<string, class-string<ServiceProvider>> $alreadyRegistered
66     */
67    private array $alreadyRegistered = [];
68    /**
69     * @var array<string, array<int, class-string<ServiceProvider>>> $dependencies
70     */
71    private array $dependencies = [
72        'enable_ai_instructor' => [
73            AiInstructorServiceProvider::class,
74        ],
75        'enable_basic_auth' => [
76            AddBasicAuthServiceProvider::class,
77        ],
78        'enable_common_plugin' => [
79            ApieCommonPluginServiceProvider::class,
80        ],
81        'enable_cms' => [
82            CommonServiceProvider::class,
83            HtmlBuilderServiceProvider::class, // it's important that this loads before CmsServiceProvider!!!
84            CmsServiceProvider::class,
85            SerializerServiceProvider::class,
86        ],
87        'enable_cms_dropdown' => [
88            CommonServiceProvider::class,
89            CmsDropdownServiceProvider::class,
90        ],
91        'enable_core' => [
92            CoreServiceProvider::class,
93        ],
94        'enable_console' => [
95            CommonServiceProvider::class,
96            ConsoleServiceProvider::class, // it's important that this loads after CommonServiceProvider!!!
97            SerializerServiceProvider::class,
98        ],
99        'enable_doctrine_entity_converter' => [
100            CoreServiceProvider::class,
101            DoctrineEntityConverterProvider::class,
102        ],
103        'enable_doctrine_entity_datalayer' => [
104            CoreServiceProvider::class,
105            DoctrineEntityConverterProvider::class,
106            DoctrineEntityDatalayerServiceProvider::class,
107        ],
108        'enable_export' => [
109            SerializerServiceProvider::class,
110            ExportServiceProvider::class,
111        ],
112        'enable_security' => [
113            CommonServiceProvider::class,
114            SerializerServiceProvider::class,
115            SecurityServiceProvider::class,
116        ],
117        'enable_rest_api' => [
118            CommonServiceProvider::class,
119            RestApiServiceProvider::class,
120            SchemaGeneratorServiceProvider::class,
121            SerializerServiceProvider::class,
122        ],
123        'enable_faker' => [
124            FakerServiceProvider::class,
125        ],
126        'enable_maker' => [
127            MakerServiceProvider::class,
128        ],
129        'enable_mcp_server' => [
130            CommonServiceProvider::class,
131            SerializerServiceProvider::class,
132            McpServerServiceProvider::class,
133        ],
134        'enable_typescript_client_builder' => [
135            TypescriptClientBuilderServiceProvider::class,
136        ],
137        'enable_webdav' => [
138            ApieFileSystemServiceProvider::class,
139            WebdavServiceProvider::class,
140        ]
141    ];
142
143    private function autoTagHashmapActions(): void
144    {
145        $boundedContextConfig = config('apie.bounded_contexts');
146        $scanBoundedContextConfig = config('apie.scan_bounded_contexts');
147        $factory = new BoundedContextHashmapFactory(
148            $boundedContextConfig ?? [],
149            $scanBoundedContextConfig ?? [],
150            new EventDispatcher(),
151        );
152        $hashmap = $factory->create();
153        foreach ($hashmap as $boundedContext) {
154            foreach ($boundedContext->actions as $action) {
155                $class = $action->getDeclaringClass();
156                if (!$class->isInstantiable()) {
157                    continue;
158                }
159                $className = $class->name;
160                TagMap::register(
161                    $this->app,
162                    $className,
163                    ['apie.context']
164                );
165            }
166        }
167    }
168
169    public function boot(): void
170    {
171        $this->autoTagHashmapActions();
172        $this->loadViewsFrom(__DIR__ . '/../templates', 'apie');
173        $this->loadRoutesFrom(__DIR__.'/../resources/routes.php');
174        TagMap::registerEvents($this->app);
175
176        if ($this->app->runningInConsole()) {
177            $commands = [];
178            $commands[] = ApieUpdateIdfCommand::class;
179            // for some reason these are not called in integration tests without re-registering them
180            foreach (TagMap::getServiceIdsWithTag($this->app, 'console.command') as $taggedCommand) {
181                $serviceId = 'apie.console.tagged.' . $taggedCommand;
182                $this->app->singleton($serviceId, function () use ($taggedCommand) {
183                    return $this->app->get($taggedCommand);
184                });
185                $commands[] = $serviceId;
186            }
187            /** @var CommonConsoleCommandFactory $factory */
188            $factory = $this->app->get('apie.console.factory');
189            foreach ($factory->create($this->app->get(Application::class)) as $command) {
190                $serviceId = 'apie.console.registered.' . $command->getName();
191                $this->app->instance($serviceId, $command);
192                $commands[] = $serviceId;
193            }
194            $this->commands($commands);
195        }
196    }
197
198    public function register()
199    {
200        $this->mergeConfigFrom(__DIR__ . '/../resources/apie.php', 'apie');
201
202        $this->app->bind(FrameworkContextBuilder::class, function () {
203            return new FrameworkContextBuilder('laravel');
204        });
205        TagMap::register($this->app, FrameworkContextBuilder::class, ['apie.core.context_builder']);
206
207        // add PSR-14 support if needed:
208        if (!$this->app->bound(EventDispatcherInterface::class)) {
209            $this->app->bind(EventDispatcherInterface::class, function () {
210                return new class($this->app->make(Dispatcher::class)) implements EventDispatcherInterface {
211                    public function __construct(private readonly Dispatcher $dispatcher)
212                    {
213                    }
214
215                    public function dispatch(object $event): object
216                    {
217                        $this->dispatcher->dispatch($event);
218                        return $event;
219                    }
220                };
221            });
222        }
223
224        // fix for https://github.com/laravel/framework/issues/30415
225        $this->app->extend(
226            ServerRequestInterface::class,
227            function (ServerRequestInterface $psrRequest) {
228                $route = $this->app->make('request')->route();
229                if ($route) {
230                    $parameters = $route->parameters();
231                    foreach ($parameters as $key => $value) {
232                        $psrRequest = $psrRequest->withAttribute($key, $value);
233                    }
234                }
235                return $psrRequest;
236            }
237        );
238
239        $this->app->bind(IndexStrategyInterface::class, function () {
240            $config = config();
241            if ($config->get('apie.enable_doctrine_entity_datalayer')) {
242                $type = $config->get('apie.doctrine.indexing.type', 'direct');
243                return match ($type) {
244                    'direct' => new DirectIndexStrategy($this->app->get(EntityReindexer::class)),
245                    'late' => new IndexAfterResponseIsSentStrategy($this->app->get(EntityReindexer::class)),
246                    'background' => new BackgroundIndexStrategy(),
247                    default => $this->app->get(config('apie.doctrine.indexing.service', DirectIndexStrategy::class)),
248                };
249            }
250
251            return new DirectIndexStrategy($this->app->get(EntityReindexer::class));
252        });
253
254        $this->app->bind(ApieErrorRenderer::class, function () {
255            return new ApieErrorRenderer(
256                $this->app->bound(CmsErrorRenderer::class) ? $this->app->make(CmsErrorRenderer::class) : null,
257                $this->app->make(\Apie\Common\ErrorHandler\ApiErrorRenderer::class),
258                config('apie.cms.base_url')
259            );
260        });
261
262        $this->app->extend(ExceptionHandler::class, function (ExceptionHandler $service) {
263            return new Handler($this->app, $service);
264        });
265
266        $this->app->bind(LockFactory::class, function () {
267            $config = config('apie.lock_store');
268            return new LockFactory($this->app->get($config));
269        });
270        
271        $this->app->bind(DashboardContentFactoryInterface::class, DashboardContentFactory::class);
272        $this->app->bind(BoundedContextSelection::class, BoundedContextSelected::class);
273
274        $this->alreadyRegistered = [];
275        $parsedConfig = $this->parseConfig(config('apie'));
276        foreach ($this->dependencies as $configKey => $dependencies) {
277            if ($parsedConfig[$configKey] ?? false) {
278                foreach ($dependencies as $dependency) {
279                    if (!isset($this->alreadyRegistered[$dependency])) {
280                        $this->alreadyRegistered[$dependency] = $dependency;
281                        $this->app->register($dependency);
282                    }
283                }
284            }
285        }
286
287        //$this->app->bind(CsrfTokenProvider::class, CsrfTokenContextBuilder::class);
288        TagMap::register($this->app, CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
289        $this->app->tag(CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
290
291        // this has to be added after CsrfTokenContextBuilder!
292        $this->app->bind(SessionContextBuilder::class);
293        TagMap::register($this->app, SessionContextBuilder::class, ['apie.core.context_builder']);
294        $this->app->tag(SessionContextBuilder::class, ['apie.core.context_builder']);
295
296        TagMap::register($this->app, RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
297        $this->app->tag(RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
298        $this->app->extend('config', function (Repository $config) {
299            $this->sanitizeConfig($config);
300            $newParsedConfig = $config->get('apie');
301            foreach ($this->dependencies as $configKey => $dependencies) {
302                if ($newParsedConfig[$configKey] ?? false) {
303                    foreach ($dependencies as $dependency) {
304                        if (!isset($this->alreadyRegistered[$dependency])) {
305                            $this->alreadyRegistered[$dependency] = $dependency;
306                            $this->app->register($dependency);
307                        }
308                    }
309                }
310            }
311            return $config;
312        });
313
314        TagMap::register($this->app, BackgroundProcessPersistListener::class, ['kernel.event_subscriber']);
315    }
316
317    /**
318     * @param array<string, mixed> $rawConfig
319     * @return array<string, mixed>
320     */
321    private function parseConfig(array $rawConfig): array
322    {
323        $path = storage_path('framework/cache/apie-config' . md5(json_encode($rawConfig)) . '.php');
324        $resources = [
325            new ReflectionClassResource(new \ReflectionClass(LaravelConfiguration::class)),
326            new ReflectionClassResource(new \ReflectionClass(static::class)),
327        ];
328        $configCache = new ConfigCache($path, true);
329        if ($configCache->isFresh()) {
330            $processedConfig = require $path;
331        } else {
332            $configuration = new LaravelConfiguration();
333
334            $processor = new Processor();
335
336            $processedConfig = $processor->processConfiguration($configuration, ['apie' => $rawConfig]);
337
338            if (!isset($processedConfig['scan_bounded_contexts'])) {
339                $processedConfig['scan_bounded_contexts'] = [];
340            }
341            if (empty($processedConfig['storage'])) {
342                $processedConfig['storage'] = null;
343            }
344            $code = '<?php' . PHP_EOL . 'return ' . var_export($processedConfig, true) . ';';
345            $configCache->write($code, $resources);
346        }
347
348        return $processedConfig;
349    }
350
351    private function sanitizeConfig(Repository $config): void
352    {
353        $rawConfig = $config->get('apie');
354        $processedConfig = $this->parseConfig($rawConfig);
355
356        $config->set('apie', $processedConfig);
357    }
358}